package handler

import (
	"booking/common/handler"
	"booking/common/validator"
	"booking/models"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func GetOrderStats(c *gin.Context) {
	db := models.Db // 你在 models 初始化时应有全局 db 实例

	//statType := c.DefaultQuery("type", "daily")
	//startStr := c.Query("start")
	//endStr := c.Query("end")

	var params struct {
		Type  string `json:"type" binding:"required"`
		Start string `json:"start"`
		End   string `json:"end"`
	}

	if err := c.ShouldBindJSON(&params); err != nil {
		handler.Error(validator.Translate(err), c)
		return
	}

	var startDate, endDate time.Time
	var err error

	// 处理日期范围
	switch params.Type {
	case "daily":
		endDate = time.Now()
		startDate = endDate.AddDate(0, 0, -7) // 最近7天
	case "weekly":
		endDate = time.Now()
		startDate = endDate.AddDate(0, 0, -7*4) // 最近4周
	case "monthly":
		endDate = time.Now()
		startDate = endDate.AddDate(0, -6, 0) // 最近6个月
	case "yearly":
		endDate = time.Now()
		startDate = endDate.AddDate(-5, 0, 0) // 最近5年
	case "custom":
		if params.Start == "" || params.End == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "custom 模式下需要 start 和 end 参数"})
			return
		}
		startDate, err = time.Parse("2006-01-02", params.Start)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "start 参数格式错误"})
			return
		}
		endDate, err = time.Parse("2006-01-02 15:04:05", params.End+" 23:59:59")
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "end 参数格式错误"})
			return
		}
	default:
		c.JSON(http.StatusBadRequest, gin.H{"error": "type 参数无效"})
		return
	}

	// 查询数据
	var stats []models.OrderStats
	if err := db.Model(&models.OrderStats{}).
		Where("stat_type = ?", params.Type).
		Where("stat_date BETWEEN ? AND ?", startDate, endDate).
		Order("stat_date ASC").
		Find(&stats).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusOK, gin.H{"xAxis": []string{}, "series": gin.H{}})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 组装 ECharts 数据结构
	var (
		xAxis         []string
		totalAmount   []float64
		status1Amount []float64
		status2Amount []float64
		status3Amount []float64
		status4Amount []float64
		totalCount    []int
		status1Count  []int
		status2Count  []int
		status3Count  []int
		status4Count  []int
	)

	for _, s := range stats {
		xAxis = append(xAxis, s.StatDate.Format("2006-01-02"))
		totalAmount = append(totalAmount, s.TotalAmount)
		status1Amount = append(status1Amount, s.Status1Amount)
		status2Amount = append(status2Amount, s.Status2Amount)
		status3Amount = append(status3Amount, s.Status3Amount)
		status4Amount = append(status4Amount, s.Status4Amount)
		totalCount = append(totalCount, s.TotalCount)
		status1Count = append(status1Count, s.Status1Count)
		status2Count = append(status2Count, s.Status2Count)
		status3Count = append(status3Count, s.Status3Count)
		status4Count = append(status4Count, s.Status4Count)
	}
	statsData, _ := getOrderSummary()
	handler.Success(map[string]any{
		"stats": statsData,
		"xAxis": xAxis,
		"series": map[string]any{
			"totalAmount":   totalAmount,
			"status1Amount": status1Amount,
			"status2Amount": status2Amount,
			"status3Amount": status3Amount,
			"status4Amount": status4Amount,
			"totalCount":    totalCount,
			"status1Count":  status1Count,
			"status2Count":  status2Count,
			"status3Count":  status3Count,
			"status4Count":  status4Count,
		},
	}, c)
}

type OrderStatsResult struct {
	TotalCount    int64   `json:"total_count"`
	TotalAmount   float64 `json:"total_amount"`
	Status1Count  int64   `json:"status_1_count"`
	Status1Amount float64 `json:"status_1_amount"`
	Status2Count  int64   `json:"status_2_count"`
	Status2Amount float64 `json:"status_2_amount"`
	Status3Count  int64   `json:"status_3_count"`
	Status3Amount float64 `json:"status_3_amount"`
	Status4Count  int64   `json:"status_4_count"`
	Status4Amount float64 `json:"status_4_amount"`
}

func getOrderSummary() (*OrderStatsResult, error) {
	var db = models.Db
	result := &OrderStatsResult{}

	// 统计总数量 & 总金额
	if err := db.Model(&models.Order{}).
		Select("COUNT(*) as total_count, COALESCE(SUM(total_amount),0) as total_amount").
		Scan(result).Error; err != nil {
		return nil, err
	}

	// 各状态数量 & 金额统计
	statuses := []int{1, 2, 3, 4}
	for _, status := range statuses {

		// ⭐⭐⭐ 每次都重新创建 query（关键）
		query := db.Model(&models.Order{})

		var count int64
		var amount float64

		if err := query.
			Where("status = ?", status).
			Select("COUNT(*) as count, COALESCE(SUM(total_amount),0) as amount").
			Row().
			Scan(&count, &amount); err != nil {
			return nil, err
		}

		switch status {
		case 1:
			result.Status1Count = count
			result.Status1Amount = amount
		case 2:
			result.Status2Count = count
			result.Status2Amount = amount
		case 3:
			result.Status3Count = count
			result.Status3Amount = amount
		case 4:
			result.Status4Count = count
			result.Status4Amount = amount
		}
	}

	return result, nil
}
